package com.kawa.shardingjdbc.controller;

import com.kawa.shardingjdbc.entity.OrderEntity;
import com.kawa.shardingjdbc.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class OrderController {
	@Autowired
	private OrderRepository orderRepository;

	// 查询所有的订单信息
	@GetMapping("/getOrderAll")
	public List<OrderEntity> getOrderAll() {
		List<OrderEntity> listOrder = (List<OrderEntity>) orderRepository.findAll();
		System.out.println("总数：" + listOrder.size());
		return listOrder;
	}

	@GetMapping("/findIdByOrder/{id}")
	public Optional<OrderEntity> findIdByOrder(@PathVariable Long id) {
		return orderRepository.findById(id);
	}

	@GetMapping("/findIdByUserId/{userId}")
	public List<OrderEntity> findIdByUserId(@PathVariable Long userId) {
		return orderRepository.findByUserId(userId);
	}

	// 使用in条件查询
	@GetMapping("/inOrder/{idStart}/{idEnd}")
	public List<OrderEntity> inOrder(@PathVariable Long idStart, @PathVariable Long idEnd) throws Exception {
		if(idStart > idEnd){
			throw new Exception("idStart > idEnd  exception!");
		}
		Long i = idStart;
		List<Long> ids = new ArrayList<>();
		while(i < idEnd ){
			ids.add(i++);
		}
		return orderRepository.findExpiredOrderState(ids);

	}

	// 增加
	@PostMapping("/inserOrder")
	public String insertOrder(@RequestBody OrderEntity orderEntity) {
		orderRepository.save(orderEntity);
		return "success";
	}

}
